// login/login/login.js
let App = getApp();
var that;
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		canIUse: wx.canIUse('button.open-type.getUserInfo'),
     instructionBook: '',
    radioCheck: true

	},
  radioClick: function (event) {
    var radioCheck = this.data.radioCheck;
    this.setData({ "radioCheck": !radioCheck });
  },
  onLoad:function(option){
    let islogin = wx.getStorageSync('access_token')
  
    if (islogin) {
      wx.switchTab({
        url: '../../shop/index/index'
      });
    } else {
      // that.isreg()
    }


    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              console.log(res.userInfo)
            }
          })
        }
      }
    })
  },
	//判断是否登陆
	isreg() {
		var that = this;
		wx.login({
			success: function(res) {
				console.log(res)
				wx.request({
					url: 'https://sc.tangmu.xin/addons/litestore/api.user/checkUserReg',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					dataType: 'json',
					data: {
						code: res.code
					},
					success: function(lres) {
						wx.setStorageSync('session_key', lres.data.data.session_key);
            wx.setStorageSync('openid', lres.data.data.openid);
						if (lres.data.ret == 200) {
							// wx.setStorageSync('access_token', lres.data.data.access_token.access_token);
	
							// wx.switchTab({
							// 	url: '../../shop/index/index',
							// })
	
						} else if (lres.data.ret == 201) {
							that.login(lres.data.data.openid, lres.data.data.session_key)
						}else{
						console.log('失败')
					}
	
					}
				})
			},
		})
	
	},
	//登录
	login(openid, session_key) {
		wx.request({
			url: 'https://sc.tangmu.xin/addons/litestore/api.user/userReg',
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			dataType: 'json',
			data: {
        openid: openid,
        session_key: session_key,
        nickname: wx.getStorageSync('userInfo.nickName'),
        avatar: wx.getStorageSync('userInfo.avatar'),
			},
			success: function(lres) {
	
        if (lres.data.ret == 200) {

          wx.setStorageSync('access_token', lres.data.data.access_token);
          wx.showToast({
            title: '登陆成功',
            icon: 'success',
            duration: 2000
          })

          // 跳转首页
          // setTimeout(function () {
          //   wx.switchTab({
          //     url: '../../shop/index/index',
          //   })
          // }, 2500)
        }
	
			}
		})
	},

  userLogin(mobile){
    wx.request({
      url: App.url.requestUrl + 'user/userLogin',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      data: {
        mobile: mobile,
        openid: wx.getStorageSync('openid')
      },
      success: function (lres) {

        if (lres.data.ret == 200) {

          wx.setStorageSync('access_token', lres.data.data.access_token);
          wx.showToast({
            title: '登陆成功',
            icon: 'success',
            duration: 2000
          })

          // 跳转首页
          setTimeout(function () {
            wx.switchTab({
              url: '../../shop/index/index',
            })
          }, 2500)
        }

      }
    })
  },
	





	// 手机号授权
	getPhoneNumber: function(e) {
		that = this;
		var sessionKey = wx.getStorageSync("session_key")
		console.log(e);
    let islogin = wx.getStorageSync('access_token')
    if (islogin){
      wx.switchTab({
				url: '../../shop/index/index'
			});
    }else{
      that.isreg()
      setTimeout(function(){
        if (e.detail.errMsg == "getPhoneNumber:ok") {
          wx.request({
            url: App.url.requestUrl + 'user/userGetPhone',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            data: {
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              sessionKey: wx.getStorageSync('session_key'), 
              open_id: wx.getStorageSync('openid'),

            },
            success: function (res) {
              console.log(res.data)
              if (res.data.ret == 200) {
                that.userLogin(res.data.data.phone)


                wx.setStorageSync('phone', res.data.data.phone);

              }else{
                wx.showToast({
                  title: '解析失败，重新解析',
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })

        }
      },1500)
      
    }
		
	
	},
	bindGetUserInfo: function(e) {
		console.log(e.detail.userInfo)
	},


	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
